package cn.edu.bjfu.practice.practice.teacher.service.impl;

import cn.edu.bjfu.practice.practice.app.component.MD5util;
import cn.edu.bjfu.practice.practice.manager.dao.UserTableDao;
import cn.edu.bjfu.practice.practice.manager.pojo.domain.UserTable;
import cn.edu.bjfu.practice.practice.student.dao.TaskDao;
import cn.edu.bjfu.practice.practice.student.pojo.domain.Task;
import cn.edu.bjfu.practice.practice.teacher.dao.*;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.*;
import cn.edu.bjfu.practice.practice.teacher.pojo.query.*;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.CourseStudentView;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.LeaderView;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.ProjectTeamView;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.SnoTaskView;
import cn.edu.bjfu.practice.practice.teacher.service.TeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.catalina.User;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    CourseDao courseDao;

    @Autowired
    StudentDao studentDao;

    @Autowired
    UserTableDao userTableDao;

    @Autowired
    ProjectDao projectDao;

    @Autowired
    TeamDao teamDao;

    @Autowired
    StudentCourseDao studentCourseDao;

    @Autowired
    StudentGroupDao studentGroupDao;

    @Autowired
    TaskDao taskDao;

    @Value("${login.password}")
    String password;

    @Override
    public void addCourse(AddCourseForm form) {
        Course course = new Course();
        course.setName(form.getName());
        course.setDate(form.getDate().toString());
        course.setTeacher_id(form.getTeacher_id());
        course.setGrade(form.getGrade());
        courseDao.insert(course);
    }

    @Override
    public void deleteCourse(Integer id) {
        Course course = new Course();
        course.setId(id);
        course.setDeleted(true);
        courseDao.updateById(course);
    }

    @Override
    public void fileCourse(FileCourseForm form) {
        Course course = new Course();
        course.setId(form.getId());
        course.setFile(form.getFile());
        courseDao.updateById(course);
    }

    @Override
    public List<Course> selectCourse(Boolean file, Integer teacher_id) {
        HashMap<String, Object> map = new HashMap();
        map.put("file", file);
        map.put("teacher_id", teacher_id);
        map.put("deleted", false);
        return courseDao.selectByMap(map);
    }

    @Override
    public List<Student> addStudent(MultipartFile excel, Integer course_id) throws IOException {
        //创建临时文件存储excel
        File tempFile = File.createTempFile( "./1", "xlsx");
        excel.transferTo(tempFile);

        //将临时文件转为XSSFWorkbook格式
        InputStream fileInput = new FileInputStream(tempFile);
        XSSFWorkbook workbook = new XSSFWorkbook(fileInput);
        int sheetIndex = 0;

        List<Student> students = new LinkedList<>();
        //循环excel文件中的每一个sheet
        for(XSSFSheet sheet; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
            sheet = workbook.getSheetAt(sheetIndex);

            //读取sheet表中的每一行
            for (Row row : sheet) {

                if(row.getRowNum() < 3)
                    continue;
                //输出每一行的第一列数据
                System.out.println(row.getCell(2).toString()+row.getCell(3).toString()+row.getCell(4).toString());
                UserTable userTable = new UserTable();
                userTable.setPassword(MD5util.encode(password));
                userTable.setType(0);
                userTableDao.insert(userTable);

                Student student = new Student();
                student.setId(userTable.getId());
                student.setName(row.getCell(2).toString());
                student.setSex(!row.getCell(3).toString().equals("男"));
                student.setGrade(row.getCell(4).toString());
                studentDao.insert(student);

                StudentCourse studentCourse = new StudentCourse();
                studentCourse.setSno(student.getId());
                studentCourse.setCourse_id(course_id);
                studentCourseDao.insert(studentCourse);
                students.add(student);
            }
        }
        //删除临时文件
        tempFile.delete();
        fileInput.close();

        return students;
    }

    @Override
    public List<CourseStudentView> selectStudent(Integer course_id) {
        return studentDao.getStudentByCourse(course_id);
    }

    @Override
    public void deleteStudent(Integer id) {
        Student student = new Student();
        student.setId(id);
        student.setDeleted(true);
        studentDao.updateById(student);
    }

    @Override
    public void updateStudent(UpdateStudentForm form) {
        Student student = new Student();
        student.setId(form.getId());
        student.setName(form.getName());
        student.setSex(form.getSex());
        student.setEmail(form.getEmail());
        student.setProfession(form.getProfession());
        student.setGrade(form.getGrade());
        studentDao.updateById(student);
    }

    @Override
    public void addProject(AddProjectForm form) {
        Project project = new Project();
        project.setName(form.getName());
        project.setIntroduce(form.getIntroduce());
        project.setNumber(form.getNumber());
        project.setNote(form.getNote());
        project.setCourse_id(form.getCourse_id());
        projectDao.insert(project);
    }

    @Override
    public void modifyProject(ModifyProjectForm form) {
        Project project = new Project();
        project.setId(form.getId());
        project.setName(form.getName());
        project.setIntroduce(form.getIntroduce());
        project.setNumber(form.getNumber());
        project.setNote(form.getNote());
        project.setCourse_id(form.getCourse_id());
        projectDao.updateById(project);
    }

    @Override
    public Integer deleteProject(Integer id) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("project_id", id);
        if(teamDao.selectByMap(map).size() > 0)
            return 0;
        else {
            Project project = new Project();
            project.setId(id);
            project.setDeleted(true);
            projectDao.updateById(project);
            return 1;
        }

    }

    @Override
    public List<Project> selectProject(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("course_id", id);
        map.put("deleted", false);
        return projectDao.selectByMap(map);
    }

    @Override
    public void addTeam(AddTeamForm form) {
        Team team = new Team();
        team.setName(form.getName());
        team.setLeader_id(form.getLeader_id());
        team.setProject_id(form.getProject_id());
        teamDao.insert(team);

        //队长与小组的关系也加入到学生小组关系表中
        StudentGroup studentGroup = new StudentGroup();
        studentGroup.setGroup_id(team.getId());
        studentGroup.setSno(team.getLeader_id());
        studentGroupDao.insert(studentGroup);
    }

    @Override
    public void modifyTeam(ModifyTeamForm form) {

        //删除原队长
        Team oldTeam = teamDao.getTeamById(form.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("sno", oldTeam.getLeader_id());
        map.put("group_id", oldTeam.getId());
        studentGroupDao.deleteByMap(map);

        //更新队伍信息
        Team team = new Team();
        team.setId(form.getId());
        team.setName(form.getName());
        team.setProject_id(form.getProject_id());
        team.setLeader_id(form.getLeader_id());
        teamDao.updateById(team);

        //队长与小组的关系也加入到学生小组关系表中
        StudentGroup studentGroup1 = new StudentGroup();
        studentGroup1.setGroup_id(team.getId());
        studentGroup1.setSno(team.getLeader_id());
        studentGroupDao.insert(studentGroup1);
    }

    @Override
    public Integer deleteTeam(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("deleted", false);
        map.put("group_id", id);
        if(studentGroupDao.selectByMap(map).size() > 1)     //除组长外还有人加入
            return 0;
        else {
            map.remove("deleted");
            studentGroupDao.deleteByMap(map);
            Team team = new Team();
            team.setId(id);
            team.setDeleted(true);
            teamDao.updateById(team);
            return 1;
        }
    }

    @Override
    public List<ProjectTeamView> selectTeam(Integer id) {
        return teamDao.selectTeam(id);
    }

    @Override
    public SnoTaskView selectTask(SelectTaskForm form) {

        Student student = studentDao.selectById(form.getSno());
        SnoTaskView snoTaskView = new SnoTaskView();
        snoTaskView.setName(student.getName());
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("sno", form.getSno());
        snoTaskView.setAllTask(taskDao.selectCount(wrapper));
        wrapper.eq("status", 2);
        snoTaskView.setDoneTask(taskDao.selectCount(wrapper));
        snoTaskView.setTasks(taskDao.getTaskByUser(form.getSno(), form.getStatus()));
        return snoTaskView;
    }

    @Override
    public List<LeaderView> selectTeamLeader(Integer course_id) {
        return studentDao.getTeamLeaders(course_id);
    }

    @Override
    public void addSingleStu(AddStudentForm form) {
        UserTable userTable = new UserTable();
        userTable.setType(0);
        userTable.setPassword(MD5util.encode(password));
        userTableDao.insert(userTable);

        Student student = new Student();
        student.setId(userTable.getId());
        student.setName(form.getName());
        student.setSex(form.getSex());
        student.setGrade(form.getGrade());
        studentDao.insert(student);

        StudentCourse studentCourse = new StudentCourse();
        studentCourse.setSno(student.getId());
        studentCourse.setCourse_id(form.getCourse_id());
        studentCourseDao.insert(studentCourse);
    }
}
